package com.TTBook.Interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.TTBook.utils.StatusConstants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 针对用户登录认证进行用户状态拦截
 * 
 * @author wenyf
 * 
 */
public class UserInterceptor extends BaseInterceptor
{

	private static final long serialVersionUID = 2642013295077600189L;
	private static final Logger log = LoggerFactory.getLogger(UserInterceptor.class);
	

	public String intercept(ActionInvocation actionInvocation) throws Exception
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if(session != null && session.getAttribute(StatusConstants.SESSION_KEY) != null)
		{
			return actionInvocation.invoke();
		}
		setToGoingURL(request, session, actionInvocation);
		return "memberBegin";
	}
	
	
	private void setToGoingURL(HttpServletRequest request,HttpSession session,ActionInvocation invocation)   
    {   
        //如果referer不为空 直接使用它。如果为空我们分别获得命名空间，action名,以及请求参数   
        //从新构造成一个URL保存在session中   
        String url=request.getHeader("referer");   
        log.info("待转向URL:"+request.getHeader("referer"));   
        if(url==null || url.equals(""))   
            {   
                url="";   
                String path=request.getContextPath();   
                String actionName=invocation.getProxy().getActionName();   
                String nameSpace=invocation.getProxy().getNamespace();   
                url = url+"/"+actionName+".do"+"?";   
                Map<String,String[]> zzMap = request.getParameterMap();   
                if(zzMap!=null)   
                    {   
                        for(String s:zzMap.keySet())   
                            {   
                                String[] value=zzMap.get(s);   
                                for(String val:value)   
                                    {   
                                        url=url+s+"="+val+"&";   
                                    }             
                            }   
                    }   
                log.info("访问的URL:"+url);   
            }   
               session.setAttribute(StatusConstants.GOTO_URL_KEY, url);   
    }
}
